package
{
	import caurina.transitions.Tweener;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.StageQuality;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.filters.DropShadowFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.ui.Mouse;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import org.papervision3d.core.math.NumberUV;
	import org.papervision3d.core.proto.MaterialObject3D;
	import org.papervision3d.core.render.data.RenderHitData;
	import org.papervision3d.core.utils.virtualmouse.VirtualMouse;
	import org.papervision3d.events.InteractiveScene3DEvent;
	import org.papervision3d.materials.BitmapMaterial;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.materials.MovieMaterial;
	import org.papervision3d.materials.utils.MaterialsList;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.parsers.Collada;
	import org.papervision3d.render.BasicRenderEngine;
	import org.papervision3d.render.QuadrantRenderEngine;
	import org.papervision3d.view.BasicView;
	import org.papervision3d.view.layer.ViewportLayer;
	
	[SWF(width="550", height="400", backgroundColor="#ffffff", frameRate="60")]
	
	/**
	 * @author Cz
	 */ 
	public class MID extends BasicView
	{
		//		==============================================
		//														状态机
		/**是否动态渲染*/		
		private var dynRender	:Boolean = true;
		/**键盘按键是否被按下*/
		private var isKeyPressed	:Boolean = false;
		/**判断鼠标是否*/
		private var focusOnTouchPad		:Boolean = false;
		//		==============================================
		//														状态机
		private var sortMode:Array = new Array();
		private const statsFormat:TextFormat = new TextFormat("微软雅黑", 10, 0xfffffe, false, false, false);
		
		private var stats:Array = new Array();
		private var sortMethod:uint = 0;
		
		private var shadowFilter:DropShadowFilter = new DropShadowFilter(-25, 15, 0x333333, .6, 30, 30, 1, 1);
		private var keylay:Array = new Array;
		//		==============================================
		//														材质
		private var canvas:Sprite = new Sprite;
		private var textArea:TextField = new TextField();
		private var windows:Array = new Array();
		private var virtualMouse:VirtualMouse;
		private var mc:Sprite = new Sprite();
		private var timer:Timer;
		private const screenSize:Rectangle = new Rectangle(0, 0, 1024, 600);
		private var material_bitmap			:BitmapMaterial;
		private var material_touchpad			:ColorMaterial;
		private var material_invisible			:MaterialObject3D = new MaterialObject3D;
		private var material_interactive_mm	:MovieMaterial;
		//		==============================================
		//														模型，贴图，及其他资源
		[Embed(source = '../asset/baked_texture_768_neo.jpg')]
		private var asset_texture:Class;		
		private var texture:Bitmap = new asset_texture() as Bitmap;
		
		[Embed(source = '../asset/arrow.gif')]
		private var asset_cursorArrow:Class;		
		private var cursor:Bitmap = new asset_cursorArrow() as Bitmap;
		
		[Embed(source = '../asset/button.gif')]
		private var asset_cursorButton:Class;
		private var cursor_button:Bitmap = new asset_cursorButton() as Bitmap;
		
		[Embed(source = '../asset/desk.png')]
		private var asset_wallpaper:Class;		
		private var wallpaper:Bitmap = new asset_wallpaper() as Bitmap;
		
		[Embed(source = '../asset/icon_painter.png')]
		private var asset_icon_painter:Class;		
		private var BM_icon_painter:Bitmap = new asset_icon_painter as Bitmap;
		private var icon_painter:Sprite = new Sprite();
		
		[Embed(source = '../asset/icon_notepad.png')]
		private var asset_icon_notepad:Class;
		private var BM_icon_notepad:Bitmap = new asset_icon_notepad() as Bitmap;
		private var icon_notepad:Sprite = new Sprite();
		
		[Embed(source = '../asset/notepadUI.gif')]
		private var asset_notepad:Class;		
		private var BM_notepad:Bitmap = new asset_notepad() as Bitmap;
		
		[Embed(source = '../asset/painter.png')]
		private var asset_painter:Class;		
		private var BM_painter:Bitmap = new asset_painter() as Bitmap;
		
		[Embed(source = '../asset/x.png')]
		private var asset_x:Class;		
		private var BM_x:Bitmap = new asset_x() as Bitmap;
		private var btn_x:Sprite = new Sprite();
		
		[Embed(source="../asset/fps.swf")]
		private var statsAsset:Class;
		private var statsView:Sprite = new statsAsset() as Sprite;
		
		[Embed(source="../asset/background.swf")]
		private var backgroundAsset:Class;
		private var background:Sprite = new backgroundAsset() as Sprite;
		
		[Embed(source="../asset/X.DAE", mimeType = "application/octet-stream")]
		
		private var modelAsset					:Class;
		private var modelBA					:ByteArray = new modelAsset() as ByteArray;
		private var model							:Collada;
		
		//		==============================================
		//														状态机
		private var helper_bas								:DisplayObject3D;
		private var helper_scr								:DisplayObject3D;
		private var helper_piv								:DisplayObject3D;
		private var helper_frg								:DisplayObject3D;
		private var group_keyboard							:DisplayObject3D;
		private var base_top								:DisplayObject3D;
		private var base_touchPad							:DisplayObject3D;
		private var base_rightBtn							:DisplayObject3D;
		private var base_leftBtn							:DisplayObject3D;
		private var base_buttom							:DisplayObject3D;		
		private var group_scrNpiv							:DisplayObject3D;
		private var piv_top									:DisplayObject3D;
		private var piv_btm									:DisplayObject3D;
		private var group_scr									:DisplayObject3D;
		private var scr_fro										:DisplayObject3D;
		private var scr_bak										:DisplayObject3D;
		private var scr_mid										:DisplayObject3D;
		private var scr_LCD										:DisplayObject3D;
		private var scr_fringe										:DisplayObject3D;
		
		private var p_piv_top										:DisplayObject3D;
		private var p_piv_btm										:DisplayObject3D;
		private var p_scr_fro										:DisplayObject3D;
		private var p_scr_bak										:DisplayObject3D;
		private var p_scr_mid										:DisplayObject3D;
		private var p_scr_LCD										:DisplayObject3D;
		private var p_scr_fringe									:DisplayObject3D;
		
		private var frag_rit										:DisplayObject3D;
		private var frag_lft										:DisplayObject3D;
		private var p_frag_rit									:DisplayObject3D;
		private var p_frag_lft									:DisplayObject3D;
		
		private var sz_bas					:uint;
		private var sz_scr					:uint;
		private var sz_piv					:uint;
		private var sz_frg					:uint;
		private var pressing				:uint = 0;
		//		==============================================
		//														分层
		private var lay_scr								:ViewportLayer;
		private var lay_scr_fro							:ViewportLayer;
		private var lay_scr_bak							:ViewportLayer;
		private var lay_scr_mid							:ViewportLayer;
		private var lay_scr_fringe							:ViewportLayer;
		private var lay_piv								:ViewportLayer;
		private var lay_piv_btm							:ViewportLayer;		
		private var lay_bas_keyboard						:ViewportLayer;
		private var lay_bas_top							:ViewportLayer;
		private var lay_bas_btm							:ViewportLayer;	
		private var lay_frag_rit							:ViewportLayer;
		private var lay_frag_lft							:ViewportLayer;
		private var lay_btm_l								:ViewportLayer;
		private var lay_btm_r								:ViewportLayer;
		private var lay_tp									:ViewportLayer;
		private var point_lst				:Point = new Point();
		private var point_cur				:Point = new Point();
		private var point_dif				:Point = new Point();
		
		private var point_lstVM			:Point = new Point();
		private var point_curVM			:Point = new Point();
		private var point_difVM			:Point = new Point();		
		private var screenRenderList			:Array;
		
		public function MID()
		{
			super(550,400,false,true,'Target');			
			init();
			creatMaterials();
			creatModel();
		}
		private function init():void
		{
			stage.quality = StageQuality.MEDIUM;
			removeChild(viewport);
			addChild(background);
			addChild(viewport);
			addChild(statsView);
			viewport.containerSprite.sortMode = 'index';
			viewport.filters = [shadowFilter];
			virtualMouse = viewport.interactiveSceneManager.virtualMouse;
			virtualMouse.ignore(cursor);
			var defaultText:Array = ['动态分层', '动态渲染'];
			for (var i:int = 0; i < 2; i++)
			{
				var tf:TextField = new TextField();
				tf.x = 66;
				tf.y = (i+1)*16.95;
				tf.width = 90;
				tf.defaultTextFormat = statsFormat;
				tf.autoSize = TextFieldAutoSize.LEFT;
				tf.text = defaultText[i];
				stats.push(tf);
				stage.addChild(tf);
			}
		}
		private function creatMaterials():void
		{
			material_bitmap 			= new BitmapMaterial(texture.bitmapData, true);
			material_bitmap.smooth = true;
			material_touchpad			= new ColorMaterial(0xd9d9d9);
			material_touchpad.interactive = true;
			
			icon_painter.addChild(BM_icon_painter);
			icon_notepad.addChild(BM_icon_notepad);
			btn_x.addChild(BM_x);
			btn_x.x = 929;
			btn_x.y = 2;
			
			icon_painter.y = 5;
			icon_notepad.y = 160;
			
			mc.addChild(wallpaper);
			mc.addChild(icon_painter);
			mc.addChild(icon_notepad);
			mc.addChild(cursor);
			windows = new Array(icon_notepad, icon_painter);
			textArea.height = 575;
			textArea.width = 962;
			textArea.y = 25;
			textArea.defaultTextFormat = new TextFormat('Trebuchet MS',50,0x00066CC);
			textArea.type = TextFieldType.INPUT;
			textArea.wordWrap = true;
			textArea.maxChars = 512;
			
			canvas.cacheAsBitmap = true;
			
			material_interactive_mm = new MovieMaterial(mc, false, true, true, screenSize);
			material_interactive_mm.interactive = true;
			material_interactive_mm.smooth = true;
		}
		private function creatModel():void
		{
			model = new Collada(new XML(modelBA), new MaterialsList({mat:material_bitmap}), 0.5);	
			
			initModelParts();
			setMaterial();
			creatLayers();
			defineSortMode();
			addEventListeners();
			scene.addChild(model);
			model.rotationX = -25;
			model.rotationY = -57;
			
			startRendering();
			renderer.renderScene(scene, camera, viewport);
		}
		private function initModelParts():void
		{
			helper_scr     = model.getChildByName('_01');
			helper_piv     = model.getChildByName('_02');
			helper_bas     = model.getChildByName('_03');
			helper_frg	   = model.getChildByName('_21');
			
			scr_fro        = model.getChildByName('_04');
			scr_bak        = model.getChildByName('_05');
			scr_mid        = model.getChildByName('_06');
			scr_LCD        = model.getChildByName('_07');
			scr_fringe     = model.getChildByName('_08');
			
			piv_top        = model.getChildByName('_09');
			piv_btm		   = model.getChildByName('_10');
			
			base_top       = model.getChildByName('_11');
			base_touchPad  = model.getChildByName('_12');
			base_rightBtn  = model.getChildByName('_13');
			base_leftBtn   = model.getChildByName('_14');
			base_buttom    = model.getChildByName('_15');
			group_keyboard = model.getChildByName('_16');
			
			frag_rit	   = model.getChildByName('_19');
			frag_lft	   = model.getChildByName('_20');
			
			piv_top.meshSort = 3;
			
			base_top.meshSort = DisplayObject3D.MESH_SORT_CLOSE;
			base_buttom.meshSort = DisplayObject3D.MESH_SORT_CLOSE;
			
			model.removeChild(helper_scr);
			model.removeChild(helper_piv);
			model.removeChild(helper_frg);
			model.removeChild(scr_fro);
			model.removeChild(scr_bak);
			model.removeChild(scr_mid);
			model.removeChild(scr_LCD);
			model.removeChild(scr_fringe);
			model.removeChild(piv_top);
			model.removeChild(piv_btm);
			model.removeChild(frag_rit);
			model.removeChild(frag_lft);
			
			p_piv_top									 = new DisplayObject3D;
			p_piv_btm									 = new DisplayObject3D;
			p_scr_fro									 = new DisplayObject3D;
			p_scr_bak									 = new DisplayObject3D;
			p_scr_mid									 = new DisplayObject3D;
			p_scr_fringe								 = new DisplayObject3D;
			p_frag_rit									 = new DisplayObject3D;
			p_frag_lft									 = new DisplayObject3D;
			
			p_scr_fro.addChild(scr_fro);
			p_scr_fro.addChild(helper_piv);
			p_scr_fro.addChild(helper_scr);
			
			p_scr_bak.addChild(scr_bak);
			p_scr_mid.addChild(scr_mid);
			p_scr_fringe.addChild(scr_fringe);
			p_scr_fringe.addChild(scr_LCD);
			p_piv_top.addChild(piv_top);
			p_piv_top.addChild(helper_frg);
			p_piv_btm.addChild(piv_btm);
			p_frag_rit.addChild(frag_rit);
			p_frag_lft.addChild(frag_lft);
			
			model.addChild(p_scr_fro);
			model.addChild(p_scr_bak);
			model.addChild(p_scr_mid);
			model.addChild(p_scr_fringe);
			model.addChild(p_piv_top);
			model.addChild(p_piv_btm);
			model.addChild(p_frag_rit);
			model.addChild(p_frag_lft);
			
			//重写触摸板的UV，否则会出现坐标映射错误,即鼠标指针不能正确地反映触摸移动。
			base_touchPad.geometry.faces[0].uv = [ new NumberUV(1,0),new NumberUV(0,0),new NumberUV(0,1) ];
			base_touchPad.geometry.faces[1].uv = [ new NumberUV(1,1),new NumberUV(1,0),new NumberUV(0,1) ];
			
			p_scr_fro.rotationX = -77;
			p_scr_fro.rotationY = 47;
			
				p_scr_bak.rotationX =
				p_scr_mid.rotationX =
				p_scr_fringe.rotationX =
				p_frag_rit.rotationX =
				p_frag_lft.rotationX = p_scr_fro.rotationX;
			
				p_piv_top.rotationY =
				p_piv_btm.rotationY =
				p_scr_bak.rotationY =
				p_scr_mid.rotationY =
				p_scr_fringe.rotationY =
				p_frag_rit.rotationY =
				p_frag_lft.rotationY = p_scr_fro.rotationY;
		}
		
		/**
		 * 给辅助物体设置隐形的材质，使他们不会被渲染，但是仍然计算它们的ScreenZ。
		 */		
		private function setMaterial():void
		{
			helper_scr.material = material_invisible;
			helper_piv.material = material_invisible;
			helper_bas.material = material_invisible;
			helper_frg.material = material_invisible;
			
			scr_LCD.material = material_interactive_mm;
			base_touchPad.material = material_touchpad;
		}
		
		/**
		 * 
		 * 
		 */		
		private function creatLayers():void
		{
			lay_bas_top = viewport.getChildLayer(base_top);
			lay_bas_top.addDisplayObject3D(piv_btm);
			
			lay_bas_btm = viewport.getChildLayer(base_buttom);
			
			lay_scr_fro       =viewport.getChildLayer(p_scr_fro);
			
			lay_scr_bak       =viewport.getChildLayer(p_scr_bak);
			lay_scr_mid       =viewport.getChildLayer(p_scr_mid);
			lay_scr_mid.layerIndex = 4;
			lay_scr_fringe    =viewport.getChildLayer(p_scr_fringe);
			
			lay_piv     	  =viewport.getChildLayer(p_piv_top);
			
			lay_piv.layerIndex = 5;
			
			lay_piv_btm		= viewport.getChildLayer(p_piv_btm);
			lay_piv_btm.layerIndex = 3;
			
			lay_frag_rit	  =viewport.getChildLayer(p_frag_rit);
			lay_frag_lft	  =viewport.getChildLayer(p_frag_lft);
			lay_bas_keyboard  =viewport.getChildLayer(new DisplayObject3D);
			
			for (var i:* in group_keyboard.children)
			{
				keylay[i] = lay_bas_keyboard.getChildLayer(group_keyboard.children[i]);
			}
			
			lay_btm_l = lay_bas_top.getChildLayer(base_leftBtn);
			lay_btm_r = lay_bas_top.getChildLayer(base_rightBtn);
			
			lay_tp = viewport.containerSprite.getChildLayer(base_touchPad);
			
			//所有属于屏幕部分的分层。当只有屏幕转动时，就仅渲染这些层，以节省资源。
			screenRenderList = [
				lay_scr_fro,
				lay_scr_bak,
				lay_scr_mid,
				lay_scr_fringe,
				lay_piv,
				lay_piv_btm,
				lay_frag_rit,
				lay_frag_lft];
			
			lay_bas_btm.layerIndex = -1;
			lay_bas_top.layerIndex = 0;
			lay_tp.layerIndex = -0.5;
			lay_bas_keyboard.layerIndex = 1;
			
			lay_scr_fro.layerIndex = 8;
			lay_scr_bak.layerIndex = 6
			
			lay_scr_fringe.layerIndex = 7;
			lay_frag_rit.layerIndex = 4.5;
			lay_frag_lft.layerIndex = 5.5;
		}
		private function defineSortMode():void
		{
			sortMode[0] = function ():void
			{
				dynRender = true;
				sortMethod = 0;
				base_top.meshSort = DisplayObject3D.MESH_SORT_CLOSE;
				base_buttom.meshSort = DisplayObject3D.MESH_SORT_CLOSE;
				renderer = new BasicRenderEngine();
				viewport.containerSprite.sortMode = 'index';
				base_top.removeEventListener(InteractiveScene3DEvent.OBJECT_PRESS, basprs);
				base_buttom.removeEventListener(InteractiveScene3DEvent.OBJECT_PRESS, basprs);
				scr_fro.removeEventListener(InteractiveScene3DEvent.OBJECT_PRESS, scrprs);
				scr_bak.removeEventListener(InteractiveScene3DEvent.OBJECT_PRESS, scrprs);
				creatLayers();
				addEvtListenerToLayers();
				sort();
				renderer.renderScene(scene, camera, viewport);
				stats[0].text = '动态分层';
				stats[1].text = '动态渲染';
			}
			sortMode[1] = function ():void
			{
				dynRender = false;
				sortMethod = 1;
				removeEvtListenerFromLayers();
				lay_bas_top.removeAllLayers();
				lay_bas_keyboard.removeAllLayers();
				viewport.containerSprite.removeAllLayers();
				viewport.containerSprite.sortMode = 'z';
				base_top.meshSort = DisplayObject3D.MESH_SORT_CENTER;
				base_buttom.meshSort = DisplayObject3D.MESH_SORT_CENTER;
				base_top.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, basprs);
				base_buttom.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, basprs);
				scr_fro.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, scrprs);
				scr_bak.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, scrprs);
				stats[0].text = '画家算法';
				stats[1].text = '实时渲染';
			}
			sortMode[2] = function ():void
			{
				sortMethod = 2;
				renderer = new QuadrantRenderEngine();
				stats[0].text = '画家算法+四叉树渲染器';
			}
		}
		private function addEventListeners():void
		{
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			lay_scr_fringe.addEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			icon_notepad.addEventListener(MouseEvent.MOUSE_DOWN, icon_notepadClk);
			icon_painter.addEventListener(MouseEvent.MOUSE_DOWN, icon_painterClk);
			addEvtListenerToLayers();
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
		}
		private function addEvtListenerToLayers():void
		{
			lay_bas_top.addEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_bas_btm.addEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_scr_fro.addEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			lay_scr_bak.addEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			lay_tp.addEventListener(MouseEvent.MOUSE_DOWN, onTPPres);
			lay_btm_l.addEventListener(MouseEvent.ROLL_OVER, onMouseButtonOver);
			lay_btm_l.addEventListener(MouseEvent.MOUSE_DOWN, btmlclk);
			lay_btm_l.addEventListener(MouseEvent.ROLL_OUT, onMouseButtonOut);
			lay_btm_r.addEventListener(MouseEvent.ROLL_OVER, onMouseButtonOver);
			lay_btm_r.addEventListener(MouseEvent.ROLL_OUT, onMouseButtonOut);
			
			for each (var lay:ViewportLayer in keylay)
			{
				lay.addEventListener(MouseEvent.CLICK, onkeyclk);
			}
		}
		private function removeEvtListenerFromLayers():void
		{
			lay_bas_top.removeEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_bas_btm.removeEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_scr_fro.removeEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			lay_scr_bak.removeEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			lay_tp.removeEventListener(MouseEvent.MOUSE_DOWN, onTPPres);
			lay_btm_l.removeEventListener(MouseEvent.ROLL_OVER, onMouseButtonOver);
			lay_btm_l.removeEventListener(MouseEvent.MOUSE_DOWN, btmlclk);
			lay_btm_l.removeEventListener(MouseEvent.ROLL_OUT, onMouseButtonOut);
			lay_btm_r.removeEventListener(MouseEvent.ROLL_OVER, onMouseButtonOver);
			lay_btm_r.removeEventListener(MouseEvent.ROLL_OUT, onMouseButtonOut);
			
			for each (var lay:ViewportLayer in keylay)
			{
				lay.removeEventListener(MouseEvent.CLICK, onkeyclk);
			}
		}
		private function keyDownHandler(e:KeyboardEvent):void
		{
			stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			if (windows[2] == textArea) stage.focus = textArea;
			switch (e.keyCode)
			{
				case 'T'.charCodeAt():
					sortMode.push(sortMode.shift());
					sortMode[0]();
					break;
				case 'R'.charCodeAt():
					if (sortMethod) return;
					if (dynRender)
					{
						dynRender = false;
						stats[1].text = '实时渲染';
					}else{
						dynRender = true;
						stats[1].text = '动态渲染';
					}
					break;	
			}
		}
		private function keyUpHandler(e:KeyboardEvent):void
		{
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
		}
		private function scrprs(e:*):void
		{
			point_lst.x = mouseX;
			point_lst.y = mouseY;
			lay_scr_fro.removeEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			lay_scr_bak.removeEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, scrmov);
			
		}
		private function scrmov(e:MouseEvent):void
		{
			lay_scr_fringe.removeEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			clculateMouseMovment();
			p_scr_fro.rotationX += point_dif.y;
			p_scr_fro.rotationY += point_dif.x;
			p_scr_fro.rotationX = (p_scr_fro.rotationX > 0) ? 0 : (p_scr_fro.rotationX < -180) ? -180 : p_scr_fro.rotationX;
			p_scr_fro.rotationY = (p_scr_fro.rotationY < 0) ? 0 : (p_scr_fro.rotationY > 180) ? 180 : p_scr_fro.rotationY;
			
			p_scr_bak.rotationX =
				p_scr_mid.rotationX =
				p_scr_fringe.rotationX =
				p_frag_rit.rotationX =
				p_frag_lft.rotationX = p_scr_fro.rotationX;
			
			p_piv_top.rotationY =
				p_piv_btm.rotationY =
				
				p_scr_bak.rotationY =
				p_scr_mid.rotationY =
				p_scr_fringe.rotationY =
				p_frag_rit.rotationY =
				p_frag_lft.rotationY = p_scr_fro.rotationY;
			
			if (dynRender)
				renderer.renderLayers(scene, camera, viewport, screenRenderList);
		}
		private function onkeyclk(e:MouseEvent):void
		{
			var curlay:ViewportLayer = e.currentTarget as ViewportLayer
			var target:DisplayObject3D = curlay.displayObject3D;
			var origipos:Number = target.y;
			function rebound():void
			{
				Tweener.addTween(target, {y:origipos, time:0.1, transition:"easeInOutSine", onComplete:inPosition});
			}
			function btmclkrender(e:Event):void
			{
				renderer.renderLayers(scene, camera, viewport, [curlay]);
			}
			function inPosition():void
			{
				isKeyPressed = false;
				stage.removeEventListener(Event.ENTER_FRAME, btmclkrender);
				renderer.renderScene(scene, camera, viewport);
			}
			if (!isKeyPressed)
			{
				isKeyPressed = true;
				if (windows[2] == textArea)
				{
					textArea.appendText(target.name.charAt(3));
					renderer.renderLayers(scene, camera, viewport, [lay_scr_fringe]);
				}
				Tweener.addTween(target, {y:origipos - 10, time:0.2, transition:"easeInOutQuint", onComplete:rebound});
				stage.addEventListener(Event.ENTER_FRAME, btmclkrender);				
			}
		}
		private function btmlclk(e:MouseEvent):void
		{
			for each (var elem:DisplayObject in windows)
			{
				if (elem.hitTestObject(cursor))
					elem.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN));
			}
			renderer.renderLayers(scene, camera, viewport, [lay_scr_fringe]);
			onkeyclk(e);
		}
		private function onMouseButtonOver(e:MouseEvent):void
		{		
			focusOnTouchPad = true;
		}
		private function onMouseButtonOut(e:MouseEvent):void
		{
			focusOnTouchPad = false;
		}
		private function onTPPres(e:MouseEvent):void
		{
			point_lstVM = new Point(virtualMouse.x, virtualMouse.y);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onTPMove);
			base_touchPad.addEventListener(InteractiveScene3DEvent.OBJECT_OUT, onTPOut);
		}
		private function onTPOut(e:InteractiveScene3DEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onTPMove);
		}
		private function onTPMove(e:MouseEvent):void
		{
			point_curVM = new Point(virtualMouse.x, virtualMouse.y);
			point_difVM = point_curVM.subtract(point_lstVM);
			cursor.x += point_difVM.x *1024*5;
			cursor.y += point_difVM.y *600*5;
			point_lstVM = point_curVM;
			cursor.x = (cursor.x > 1024) ? 1024 : (cursor.x < 0) ? 0 : cursor.x;
			cursor.y = (cursor.y > 600) ? 600 : (cursor.x < 0) ? 0 : cursor.y;
			renderer.renderLayers(scene, camera, viewport, [lay_scr_fringe, lay_tp]);			
		}
		private function basprs(e:*):void
		{
			point_lst.x = mouseX;
			point_lst.y = mouseY;
			lay_bas_top.removeEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_bas_btm.removeEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_scr_fringe.removeEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			if (!focusOnTouchPad) stage.addEventListener(MouseEvent.MOUSE_MOVE, basmov); 
		}
		private function basmov(e:MouseEvent):void
		{
			clculateMouseMovment();
			model.rotationX += point_dif.y;
			model.rotationY += point_dif.x;
			if (dynRender)
				renderer.renderScene(scene, camera, viewport);
		}
		private function onMouseUp(e:MouseEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, scrmov);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, basmov);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onTPMove);
			
			lay_bas_top.addEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_bas_btm.addEventListener(MouseEvent.MOUSE_DOWN, basprs);
			lay_scr_fro.addEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			lay_scr_bak.addEventListener(MouseEvent.MOUSE_DOWN, scrprs);
			
			lay_scr_fringe.addEventListener(MouseEvent.ROLL_OVER, onOverScreen);			
			renderer.renderScene(scene, camera, viewport);			
			checkScrHit();
		}
		
		/**
		 * 动态分层
		 * 
		 */		
		private function sort():void
		{
			sz_bas = uint(helper_bas.screenZ);
			sz_scr = uint(helper_scr.screenZ);
			sz_piv = uint(helper_piv.screenZ);
			sz_frg = uint(helper_frg.screenZ);
			if (sz_bas)
			{
				lay_bas_btm.layerIndex = -1;
				lay_bas_top.layerIndex = 0;
				lay_tp.layerIndex = -0.5;
				lay_bas_keyboard.layerIndex = 1;
			}
			else
			{
				lay_bas_keyboard.layerIndex = 8;
				lay_bas_top.layerIndex = 9;
				lay_tp.layerIndex = 8.5;
				lay_bas_btm.layerIndex = 10;
			}
			if (sz_scr)
			{
				lay_scr_fro.layerIndex = 8;
				lay_scr_bak.layerIndex = 6
				if (sz_piv)
				{//fro
					lay_scr_fringe.layerIndex = 7;
				}else{
					lay_scr_fringe.layerIndex = 2;
				}
			}else{
				lay_scr_fringe.layerIndex = 2;
				lay_scr_fro.layerIndex = 6;
				lay_scr_bak.layerIndex = 8;
			}
			if (sz_frg)
			{//right
				lay_frag_rit.layerIndex = 5.5;
				lay_frag_lft.layerIndex = 4.5;
			}else{
				lay_frag_rit.layerIndex = 4.5;
				lay_frag_lft.layerIndex = 5.5;
			}
		}
		private function onOver(e:InteractiveScene3DEvent):void
		{
			//lay_scr_fringe
			//lay_scr_fringe.removeEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			//lay_scr_fringe.addEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			lay_scr_fringe.removeEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			scr_LCD.addEventListener(InteractiveScene3DEvent.OBJECT_OUT, onOut);
			viewport.addEventListener(MouseEvent.ROLL_OUT, onMouseLeave);
			Mouse.hide();
			stage.addEventListener(MouseEvent.MOUSE_MOVE, renderScreen);
		}
		private function onOverScreen(e:MouseEvent):void
		{
			checkScrHit(e);
		}
		private function onOutOfScreen(e:MouseEvent):void
		{
			scr_LCD.dispatchEvent(new InteractiveScene3DEvent(InteractiveScene3DEvent.OBJECT_OUT));
		}
		private function renderScreen(e:MouseEvent):void
		{
			cursor.x = virtualMouse.x;
			cursor.y = virtualMouse.y;
			renderer.renderLayers(scene, camera,viewport, [lay_scr_fringe]);
		}
		private function onMouseLeave(e:MouseEvent):void
		{
			scr_LCD.dispatchEvent(new InteractiveScene3DEvent(InteractiveScene3DEvent.OBJECT_OUT));
			viewport.addEventListener(MouseEvent.ROLL_OVER, checkScrHit);
		}
		private function checkScrHit(e:MouseEvent = null):void
		{
			var rhd:RenderHitData = viewport.hitTestMouse();
			if (rhd.hasHit && rhd.displayObject3D == scr_LCD)
				scr_LCD.dispatchEvent(new InteractiveScene3DEvent(InteractiveScene3DEvent.OBJECT_OVER));
		}
		
		/**
		 * 打开记事本
		 * @param e
		 * 
		 */		
		private function icon_notepadClk(e:MouseEvent):void		
		{
			icon_notepad.removeEventListener(MouseEvent.MOUSE_DOWN, icon_notepadClk);
			stage.focus = textArea;
			windows = new Array(BM_notepad, btn_x, textArea);
			for each (var element:DisplayObject in windows)
			{
				mc.addChild(element);
			}
			textArea.text = 'You can type here!';
			mc.addChild(cursor);
			textArea.addEventListener(KeyboardEvent.KEY_DOWN, type);
			btn_x.addEventListener(MouseEvent.MOUSE_DOWN, closeWindow);			
		}
		private function type(e:KeyboardEvent):void
		{	
			timer = new Timer(10, 1);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, typrRender);					
			timer.start();
		}
		private function typrRender(e:TimerEvent):void
		{
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, typrRender);
			renderer.renderLayers(scene, camera, viewport, [lay_scr_fringe]);
		}
		
		/**
		 * 关闭窗口
		 * @param e
		 * 
		 */		
		private function closeWindow(e:MouseEvent):void
		{
			for each (var elem:DisplayObject in windows)
			{
				mc.removeChild(elem);
			}
			windows = new Array(icon_notepad, icon_painter);
			textArea.text = '';
			canvas.graphics.clear();
			stage.focus = stage;
			btn_x.removeEventListener(MouseEvent.MOUSE_DOWN, closeWindow);
			icon_painter.addEventListener(MouseEvent.MOUSE_DOWN, icon_painterClk);
			icon_notepad.addEventListener(MouseEvent.MOUSE_DOWN, icon_notepadClk);
		}
		
		/**
		 * 打开画图板
		 * @param e
		 * 
		 */		
		private function icon_painterClk(e:MouseEvent):void
		{
			trace(base_touchPad.willTrigger(InteractiveScene3DEvent.OBJECT_RELEASE));
			trace(e.target);
			icon_painter.removeEventListener(MouseEvent.MOUSE_DOWN, icon_painterClk);
			canvas.graphics.lineStyle(15, 0xDD0000);
			mc.removeChild(cursor);
			windows = new Array(BM_painter, btn_x, canvas);
			for each (var element:DisplayObject in windows)
			{
				mc.addChild(element);
			}
			mc.addChild(cursor);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
			btn_x.addEventListener(MouseEvent.MOUSE_DOWN, closeWindow);
		}
		private function startDrawing(e:MouseEvent):void
		{
			if (cursor.x > 954 || cursor.y < 33) return;
			canvas.graphics.moveTo(cursor.x, cursor.y);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, drawLine);
			stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);			
		}
		private function drawLine(e:MouseEvent):void
		{
			if (cursor.x > 954 || cursor.y < 33) return;
			canvas.graphics.lineTo(cursor.x, cursor.y);
		}
		
		private function stopDrawing(e:MouseEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, drawLine);
			stage.removeEventListener(MouseEvent.MOUSE_UP, stopDrawing);
		}
		private function onOut(e:InteractiveScene3DEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, renderScreen);
			lay_scr_fringe.addEventListener(MouseEvent.ROLL_OVER, onOverScreen);
			scr_LCD.removeEventListener(InteractiveScene3DEvent.OBJECT_OUT, onOut);
			renderer.renderScene(scene, camera, viewport);
			Mouse.show();
		}
		
		/**
		 * 计算鼠标位移
		 * 
		 */		
		private function clculateMouseMovment():void
		{
			point_cur = new Point(mouseX, mouseY);
			point_dif = point_cur.subtract(point_lst);
			point_lst = point_cur;
		}
		override protected function onRenderTick(event:Event=null) : void
		{
			//是否动态分层
			if (!sortMethod) sort();	
			
			//是否动态渲染
			if (!dynRender)
			{
				super.onRenderTick();
				return;
			}
		}
	}
}